package com.smart.web.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.smart.consts.AppInteractiveState;
import com.smart.consts.AppStatusData;
import com.smart.dao.Page;
import com.smart.dao.PageRequest;
import com.smart.model.User;
import com.smart.model.UserPojo;
import com.smart.model.UserToken;
import com.smart.model.UserViewRecord;
import com.smart.model.UserViewRecordCond;
import com.smart.model.UserViewRecordPojo;
import com.smart.model.VerifyCode;
import com.smart.model.base.JsonModel;
import com.smart.util.DateUtil;
import com.smart.util.MD5;
import com.smart.util.StringUtil;

/**
 * app 个人中心处理器
 * @author zhuyong
 *
 */
@Controller
public class AppUserCenterController extends BaseController{
	/**
	 * 手机号正则表达式
	 */
	private static final Pattern MOBILE_PATTERN = Pattern.compile("^\\d{11}$");
	//注册
	@RequestMapping("appUser/register")
	public void register(String data,HttpServletRequest request, HttpServletResponse response) {
		JsonModel jsonModel = new JsonModel();
		AppStatusData statusObject = new AppStatusData();
		if (requestHandle(data, jsonModel,statusObject)) {
			String  mobile = jsonModel.getBodyValue("mobile");
			String vCode = jsonModel.getBodyValue("vCode");
			String pwd1 = jsonModel.getBodyValue("pwd1");
			String pwd2 = jsonModel.getBodyValue("pwd2");
			//检查用户是否已经注册过
			if(StringUtil.isNotEmpty(mobile) 
					&& isValidMobile(mobile)
					&& checkUserHasReged(mobile)) {
				statusObject = new AppStatusData("305", "当前手机号码已经注册过");
				returnJson(response, statusObject, null);
			}
			//检查验证码
			if(!isValidMobile(mobile)) {
				statusObject = new AppStatusData("305", "输入的手机号码格式不正确");
				returnJson(response, statusObject, null);
			}
			if(!verifyCodeService.verity(mobile, vCode)) {
				statusObject = AppInteractiveState.VCODE_REG_FAILED;
				returnJson(response, statusObject, null);
			}
			//两次密码一致性
			if(!pwd1.equals(pwd2)) {
				statusObject = new AppStatusData("305", "两次输入密码不一致");
				returnJson(response, statusObject, null);
			}
			//save
			User user = new User();
			user.setUsername(mobile);
			user.setMobilePhone(mobile);
			user.setPassword(MD5.md5Hex16(pwd1, "utf-8"));
			userService.save(user);
			statusObject=AppInteractiveState.SUCCESS_DATA;
			returnJson(response, statusObject, null);
		}
		returnJson(response, jsonModel);
	}
	//登录
	@RequestMapping("appUser/login")
	public void login(String data,HttpServletRequest request, HttpServletResponse response) {
		JsonModel jsonModel = new JsonModel();
		AppStatusData statusObject = new AppStatusData();
		if (requestHandle(data, jsonModel,statusObject)) {
			//登录方式 1:密码登录 2:验证码登录
			String type = jsonModel.getBodyValue("type");
			String mobile = jsonModel.getBodyValue("mobile");
			String code = jsonModel.getBodyValue("code");
			String pwd = jsonModel.getBodyValue("pwd");
			Map<String,String> map = new HashMap<>();
			if(!isValidMobile(mobile)) {
				statusObject=new AppStatusData("305", "请检查手机号码");
				returnJson(response, statusObject, null);
			}
			User user = userService.findOneBy("username", mobile);
			if(type.equals("1")) {
				String pwd1 = MD5.md5Hex16(pwd, "utf-8");
				if(user!=null && user.getPassword().equals(pwd1)) {
					statusObject = AppInteractiveState.SUCCESS_DATA;
					map = insertTokenToDb(user.getId());
					returnJson(response, statusObject, map);
				}else {
					statusObject = AppInteractiveState.PWD_NOT_REG;
					returnJson(response, statusObject, null);
				}
			}else if(type.equals("2")) {
				if(user != null && user.getMobilePhone().equals(mobile)) {
					VerifyCode verifyCode = verifyCodeService.findLatestOneByMobile(mobile);
					if(verifyCodeService.verity(mobile, code)) {
						verifyCode.setUsed(true);
						verifyCodeService.save(verifyCode);
						map = insertTokenToDb(user.getId());
						statusObject = AppInteractiveState.SUCCESS_DATA;
						returnJson(response, statusObject, map);
					}else {
						statusObject=new AppStatusData("305", "登录失败,验证码不匹配！");
						returnJson(response, statusObject, null);
					}
				}else {
					statusObject=new AppStatusData("305", "验证码登录失败,请检查手机号是否已经注册");
					returnJson(response, statusObject, null);
				}
			}
		}
		returnJson(response, jsonModel);
	}
	//个人信息
	@RequestMapping("appUser/myInfo")
	public void myInfo(String data,HttpServletRequest request, HttpServletResponse response) {
		JsonModel jsonModel = new JsonModel();
		AppStatusData statusObject = new AppStatusData();
		UserPojo pojo = new UserPojo();
		jsonModel.setHeaderValue("flag", "1");
		if (requestHandle(data, jsonModel,statusObject)) {
			String idStr=jsonModel.getBodyValue("id");
			if(StringUtil.isNotEmpty(idStr)) {
				Long id=Long.valueOf(idStr);
				User user = userService.findOne(id);
				if(user!=null) {
					pojo.setNickName(user.getNickName());
					pojo.setMobile(user.getMobilePhone());
					pojo.setEducational(user.getEducational());
					pojo.setSalary(user.getSalary());
					pojo.setJob(user.getJob());
					statusObject = AppInteractiveState.SUCCESS_DATA;
					returnJson(response, statusObject, pojo);
				}else {
					statusObject = new AppStatusData("305", "未找到当前人员信息");
					returnJson(response, statusObject, pojo);
				}
			}else {
				statusObject = AppInteractiveState.ERROR_FORMAT;
				returnJson(response, statusObject, null);
			}
		}
		returnJson(response, statusObject, pojo);
	}
	//浏览记录
	//个人信息
		@RequestMapping("appUser/viewHistory")
		public void viewHistory(String data,HttpServletRequest request, HttpServletResponse response) {
			JsonModel jsonModel = new JsonModel();
			AppStatusData statusObject = new AppStatusData();
			PageRequest pageRequest = new PageRequest();
			Map<String, List<UserViewRecord>> map = new HashMap<>();
			List<UserViewRecordPojo> pojos = new ArrayList<>(); 
			jsonModel.setHeaderValue("flag", "1");
			if (requestHandle(data, jsonModel,statusObject)) {
				String idStr=jsonModel.getBodyValue("id");
				String pageNumberStr=jsonModel.getBodyValue("pageNumber");
				int pageNumber = 0;
				if(StringUtil.isNotEmpty(pageNumberStr)) {
					pageNumber = Integer.valueOf(pageNumberStr);
					pageRequest.setPageNumber(pageNumber);
				}
				if(StringUtil.isNotEmpty(idStr)) {
					Long uid = Long.valueOf(idStr);
					UserViewRecordCond cond = new UserViewRecordCond();
					cond.setUserId(uid);
					Page<UserViewRecord> page = userViewRecordService.findAll(pageRequest, cond);
					List<UserViewRecord> list = page.getContent();
					for (UserViewRecord userViewRecord : list) {
						String date=userViewRecord.getTimeCreated().toString();
						date=StringUtil.isEmpty(date)?"":date.substring(0, 10);
						if(map.containsKey(date)) {
							map.get(date).add(userViewRecord);
						}else {
							List<UserViewRecord> thisTimeList = new ArrayList<>();
							thisTimeList.add(userViewRecord);
							map.put(date,thisTimeList );
						}
					}
					for (String dateKey : map.keySet()) {
						UserViewRecordPojo pojo = new UserViewRecordPojo(dateKey,map.get(dateKey));
						pojos.add(pojo);
					}
					statusObject = AppInteractiveState.SUCCESS_DATA;
					returnJson(response, statusObject, pojos);
				}else {
					statusObject = AppInteractiveState.ERROR_FORMAT;
					returnJson(response, statusObject, null);
				}
			}
			returnJson(response, statusObject, pojos);
		}
	//修改个人信息
	@RequestMapping("appUser/changeProfile")
	public void changeProfile(String data,HttpServletRequest request, HttpServletResponse response) {
		JsonModel jsonModel = new JsonModel();
		AppStatusData statusObject = new AppStatusData();
		jsonModel.setHeaderValue("flag", "1");
		if (requestHandle(data, jsonModel,statusObject)) {
			String idStr=jsonModel.getBodyValue("id");
			String nickName = jsonModel.getBodyValue("nickName");
			String mobile = jsonModel.getBodyValue("mobile");
			String educational = jsonModel.getBodyValue("educational");
			String salary = jsonModel.getBodyValue("salary");
			String job = jsonModel.getBodyValue("job");
			
			if(StringUtil.isNotEmpty(idStr)) {
				Long id=Long.valueOf(idStr);
				User user = userService.findOne(id);
				if(user!=null) {
					if(StringUtil.isNotEmpty(nickName)) {
						user.setNickName(nickName);
					}
					if(StringUtil.isNotEmpty(mobile)) {
						user.setMobilePhone(mobile);
					}
					if(StringUtil.isNotEmpty(educational)) {
						user.setEducational(educational);
					}
					if(StringUtil.isNotEmpty(salary)) {
						user.setSalary(salary);
					}
					if(StringUtil.isNotEmpty(job)) {
						user.setJob(job);
					}
					userService.save(user);
					statusObject = AppInteractiveState.SUCCESS_DATA;
				}else {
					statusObject = AppInteractiveState.BUSINESS_DATA;
				}
				returnJson(response, statusObject, null);
			}else {
				statusObject = AppInteractiveState.ERROR_FORMAT;
				returnJson(response, statusObject, null);
			}
		}
		returnJson(response, statusObject, null);
	}
	//发送验证码
	@RequestMapping("appUser/sendMsg")
	public void sendMsg(String data,HttpServletRequest request, HttpServletResponse response) {
		JsonModel jsonModel = new JsonModel();
		//jsonModel.setHeaderValue("flag", "1");
		AppStatusData statusObject = new AppStatusData();
		if (requestHandle(data, jsonModel,statusObject)) {
			String mobile = jsonModel.getBodyValue("mobile");
			if(isValidMobile(mobile)) {
				//get a code
				String code=generateCode(4);
				boolean status = verifyCodeService.sendVerifyCode(mobile, code);
				if(status) {
					VerifyCode verifyCode = new VerifyCode();
					verifyCode.setCode(code);
					verifyCode.setMobile(mobile);
					verifyCodeService.save(verifyCode);
					statusObject = AppInteractiveState.SUCCESS_DATA;
				}else {
					statusObject=new AppStatusData("305", "短信发送失败");
				}
				returnJson(response, statusObject, null);
			}
		}
		returnJson(response,statusObject,null);
	}
	private static boolean isValidMobile(String mobile) {
		Matcher matcher = MOBILE_PATTERN.matcher(mobile);
		if(StringUtil.isEmpty(mobile)) {
			return false;
		}
		if(matcher.find()){
			return true;
		}
		return false;
	}
	/**
	 * 产生随机验证码
	 * @param length 验证码长度
	 * @return
	 */
	private static String generateCode(int length){
		if(length<4 || length > 10){
			length = 4;
		}
		Random random = new Random();
		String result = "";
		for(int i=0; i< length; i++){
			result += Math.abs(random.nextInt()%10);
		}
		return result;
	}
	private boolean checkUserHasReged(String mobile) {
		boolean status=false;
		User user = userService.findOneBy("username", mobile);
		if(user!=null) {
			status = true;
		}
		return status; 
	}
	private Map<String, String>  insertTokenToDb(Long uid) {
		UserToken ut = new UserToken();
		Map<String, String> map = new HashMap<>();
		String token = UUID.randomUUID().toString();
		if(StringUtil.isNotEmpty(token)) {
			ut.setUid(uid);
			ut.setToken(token);
			Date expireTime= DateUtil.rollDate(new Date(), Calendar.MINUTE, 60*24*15);
			ut.setExpireTime(expireTime);
			userTokenService.save(ut);
			map.put("uid", uid+"");
			map.put("token", token);
		}
		return map;
	}
	public static void main(String[] args) {
		Date expireTime= DateUtil.rollDate(new Date(), Calendar.MINUTE, 60*24*15);
		System.out.println(expireTime);
	}
}
